﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Data.Objects;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLogic
{
    public delegate void CustomerChangedEventHandler(object sender, CustomerChangedEventArgs e);

    public partial class WGRUSEntities : DbContext
    {
        public event CustomerChangedEventHandler CustomerChanged;

        public override int SaveChanges()
        {
            var frame = new StackFrame();
            var method = new StackFrame(1).GetMethod().Name;

            if (method.Equals("UpdateCustomer"))
            {
                return base.SaveChanges();
            }

            //Kun GUI ændringer skal håndteres
            var autoDetectChanges = Configuration.AutoDetectChangesEnabled;

            var entries = from e in this.ChangeTracker.Entries()
                where (e.State == EntityState.Added ||
                       e.State == EntityState.Modified) &&
                      e.Entity != null &&
                      e.Entity is Customer
                select e;

            foreach (var entry in entries)
            {
                Customer cust = entry.Entity as Customer;
                switch (entry.State)
                {
                    case EntityState.Added:
                    case EntityState.Modified:
                        OnCustomerChanged(new CustomerChangedEventArgs(cust, entry.State));
                        break;
                }
            }

            return base.SaveChanges();
        }

        protected virtual void OnCustomerChanged(CustomerChangedEventArgs e)
        {
            Facade.Instance.NotifyCustomerChanged(e);
            if (CustomerChanged != null)
                CustomerChanged(this, e);
        }
    }
}